package com.atguigu.vodtest;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;

/**
 * @Author: LDeng
 * @Date: 2022-03-10 9:24 AM
 */
public class ADLogin {
    public static void main(String[] args) throws NamingException {
        String userName="LDeng";
        String password="8DL@111";
        String host="10.19.1.1";
        String domain="@intersurgical.local";
        String port="389";
        String url=new String("ldap://"+host+":"+port);
        String user= userName.indexOf(domain)>0?userName:userName+domain;
        Hashtable env=new Hashtable();
        DirContext ctx=null;
        env.put(Context.SECURITY_AUTHENTICATION,"simple");
        env.put(Context.SECURITY_PRINCIPAL,user);
        env.put(Context.SECURITY_CREDENTIALS,password);
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL,url);
        try{
            ctx=new InitialDirContext(env);
            System.out.println("身份认证成功");
        }catch (AuthenticationException e){
            System.out.println("身份认证失败");
        }catch (javax.naming.CommunicationException e){
            System.out.println("AD域连接失败");
        }catch (Exception e){
            System.out.println("其他未知异常");
        }finally {
            if(ctx!=null){
                try{
                    ctx.close();
                    ctx=null;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }


}
